<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/10 0010
 * Time: 下午 1:37
 */
namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\AdminGroup;
use think\Controller;
use app\admin\model\Menu;
use think\Model;
use think\Request;
use think\Session;

class Common extends Controller {
    /**
     * @title   初始化网站数据
     */
    public function _initialize()
    {
        if(!Session::has('adminid')){
            if(Request::instance()->isAjax()) $this->error('登陆已过期，请重新登陆');
            $this->redirect(url('login/index'));
        }

        $menu = new Menu();
        $admin = new Admin();
        $aid = Session::get('adminid');
        $gid = $admin->where('id', $aid)->value('gid');
        $ag = new AdminGroup();
        //获取用户组权限ID
        $adminrule = $rule = explode(',', $ag->where('id', $gid)->value('rule'));
        $where['id'] = array('in', $adminrule);
        //递归输出栏目
        $list = getMenu($menu->where($where)->order('sort asc')->select()->toArray());
        //检测是否有对应权限，开发组开放所有编辑按钮的权限
        if($gid!=1 && $gid!=2) {
            if (!has_menu($list)) {
                $this->error('没有权限', 'Index/index');
            }
        }
        $url = ucfirst(\think\Request::instance()->controller()).'/'. strtolower(\think\Request::instance()->action());
        v('headtitle',$menu -> where('url',$url) -> value('title'));

        //写入日志表
        action_logs($list);

        $this->assign('menu',$list);

        //侧边栏定位class
        $url = Request::instance()->controller() . '/' . Request::instance()->action();
        $active = $menu->where('url', $url)->find();
        if($active){
            session('menu',$active->toArray());
            $this->assign('active', $active->toArray());
        }else{
            $this->assign('active', session('menu'));
        }
    }

    /**
     * @param Model $model              传递模型
     * @param $data                     传递数组
     * @param $type                     0：不使用回调 1：使用回调
     * @param \Closure|null $closure    使用回调灵活操作业务
     * @param $valname                  验证器的名称
     */
    public function store(Model $model, $data, $valname=null, $type=0, \Closure $closure=null)
    {
        $res = $model->store($data, $valname);
        if($type==1) {
            $closure($res);
        }else{
            return $res;
        }
    }

    /**
     * @title   显示404页面
     */
    public function _empty (){
        if(Request::instance()->isAjax()) $this->error('请求页面未找到');
        return $this->fetch('./static/html/404.html');
        exit;
    }
}